<template>
  <layout-body>
    <el-form
      ref="createRef"
      label-width="130px"
      size="default"
      v-loading="initLoading"
      :model="createForm"
      :rules="createRules"
    >
      <el-tabs @tab-change="tabChange" v-model="tabIndex">
        <el-tab-pane label="基础信息" :name="1">
          <div class="form-main">
            <div class="form-main-item">
              <el-form-item
                class="form-main-item-input"
                label="商品分类："
                prop="cate_id"
              >
                <el-cascader
                  v-model="createForm.cate_id"
                  :options="cateData"
                  :props="{
                    multiple: true,
                    value: 'id',
                    label: 'cate_name',
                    emitPath: false,
                  }"
                  collapse-tags
                  collapse-tags-tooltip
                  clearable
                  :show-all-levels="false"
                  class="form-select-fil"
                />
              </el-form-item>
              <div class="form-main-item-btn ml20" @click="createCate">
                新增分类
              </div>
            </div>
            <div class="form-main-item">
              <el-form-item
                label="商品名称："
                prop="goods_name"
                class="form-main-item-input"
              >
                <el-input
                  v-model="createForm.goods_name"
                  placeholder="请输入商品名称"
                ></el-input>
              </el-form-item>
            </div>
            <el-form-item label="商品图：" prop="goods_imgs">
              <upload-btn
                v-model="createForm.goods_imgs"
                width="80px"
                height="80px"
                count="9"
              ></upload-btn>
              <help hideIcon
                >建议尺寸：800 *
                800px，可拖拽改变图片顺序，默认首张图为主图，最多上传9张</help
              >
            </el-form-item>
            <div class="form-main-item">
              <el-form-item
                label="商品标签："
                prop="goods_label"
                class="form-main-item-input"
              >
                <el-select
                  v-model="createForm.goods_label"
                  multiple
                  placeholder="请选择商品标签"
                  class="form-select-fil"
                >
                  <el-option
                    v-for="item in labelData"
                    :key="item.id"
                    :label="item.label_name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <div class="form-main-item-btn ml20" @click="createLabel">
                新增标签
              </div>
            </div>
            <div class="form-main-item">
              <el-form-item
                label="单位："
                prop="goods_unit"
                class="form-main-item-input"
              >
                <el-select
                  v-model="createForm.goods_unit"
                  placeholder="请选择单位"
                  class="form-select-fil"
                >
                  <el-option
                    v-for="item in unitData"
                    :key="item.id"
                    :label="item.unit_name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <div class="form-main-item-btn ml20" @click="createUnit">
                新增单位
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="规格库存" :name="2">
          <div class="form-main">
            <div class="form-main-item">
              <el-form-item
                label="商品规格："
                prop="spec_type"
                class="form-main-item-input"
              >
                <el-radio-group v-model="createForm.spec_type">
                  <template v-for="(item, index) in specTypeEnum" :key="index">
                    <el-radio :label="item.value">{{ item.name }}</el-radio>
                  </template>
                </el-radio-group>
              </el-form-item>
            </div>
            <template v-if="createForm.spec_type == 1">
              <template v-for="(item, index) in specForm" :key="index">
                <el-form-item
                  v-if="item.type !== 'image'"
                  :label="`${item.name}：`"
                  :prop="`spec[${0}].[${item.key}]`"
                  :rules="
                    item.required
                      ? [
                          {
                            required: true,
                            trigger: 'blur',
                            message: `请输入${item.name}`,
                          },
                        ]
                      : []
                  "
                  class="form-main-item-input"
                >
                  <el-input
                    :type="item.input_type ? item.input_type : 'number'"
                    v-model="createForm.spec[0][item.key]"
                    :placeholder="`请输入${item.name}`"
                  >
                    <template v-if="item.unit" #suffix>
                      {{ item.unit }}
                    </template>
                  </el-input>
                </el-form-item>
              </template>
            </template>
            <template v-else>
              <div class="form-main-item">
                <el-form-item label="规格模版：">
                  <el-select
                    placeholder="请选择商品标签"
                    v-model="specTemplatesId"
                  >
                    <el-option
                      v-for="item in specTemplatesData"
                      :key="item.id"
                      :label="item.spec_temp_name"
                      :value="item.id"
                    />
                  </el-select>
                  <el-button class="ml10" @click="selectedTemplates">
                    确定模版
                  </el-button>
                  <div
                    class="form-main-item-btn ml20"
                    @click="createSpecTemplates"
                  >
                    新增规格模板
                  </div>
                  <help hideIcon>可选择已保存的对应模版进行生成</help>
                </el-form-item>
              </div>

              <div>
                <el-form-item>
                  <storeGoodsSpec
                    v-model="specData"
                    ref="storeGoodsSpecRef"
                  ></storeGoodsSpec>
                </el-form-item>
              </div>

              <div>
                <el-form-item>
                  <div class="flex">
                    <el-input
                      class="form-main-item-small"
                      placeholder="请输入规格名"
                      v-model="specName"
                    >
                    </el-input>
                    <el-button
                      class="ml10"
                      type="primary"
                      bg
                      text
                      @click="createSpecName()"
                      >添加新规格</el-button
                    >
                    <el-button
                      class="ml10"
                      type="primary"
                      @click="saveSpec(createRef)"
                      >生成规格属性</el-button
                    >
                  </div>
                  <help hideIcon
                    >注意：生成规格属性12小时内有效，过期需重新生成</help
                  >
                </el-form-item>
              </div>
              <div v-if="createForm.spec_type == 2">
                <el-form-item prop="spec" :rules="[{ validator: specValid }]">
                  <template v-if="createForm.spec.length > 0">
                    <el-table
                      :data="createForm.spec"
                      style="width: 100%"
                      border
                    >
                      <template
                        v-for="(item, index) in headColumns"
                        :key="index"
                      >
                        <el-table-column
                          :prop="item.key"
                          :label="item.name"
                          align="left"
                        >
                          <template #default="scope">
                            <el-form-item
                              :prop="
                                item.required
                                  ? `spec[${scope.$index}].[${item.key}]`
                                  : ''
                              "
                              :rules="
                                item.required
                                  ? [
                                      {
                                        required: true,
                                        trigger: 'blur',
                                        message: `请输入${item.name}`,
                                      },
                                    ]
                                  : []
                              "
                            >
                              <template
                                v-if="item.type && item.type == 'input'"
                              >
                                <el-input
                                  v-model="scope.row[item.key]"
                                  :type="item.input_type || 'number'"
                                />
                              </template>
                              <template
                                v-else-if="item.type && item.type == 'image'"
                              >
                                <div class="spec-table-column-img">
                                  <upload-btn
                                    v-model="scope.row[item.key]"
                                    width="40px"
                                    height="40px"
                                    count="1"
                                  ></upload-btn>
                                </div>
                              </template>
                              <template v-else>
                                <template v-if="scope.row[item.key].img">
                                  <el-image
                                    style="width: 30px; height: 30px"
                                    :src="scope.row[item.key].img"
                                    fit="fill"
                                  />
                                </template>
                                <span class="ml5">
                                  {{ scope.row[item.key].name }}
                                </span>
                              </template>
                            </el-form-item>
                          </template>
                        </el-table-column>
                      </template>
                    </el-table>
                  </template>
                </el-form-item>
              </div>
            </template>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品详情" :name="3">
          <el-form-item prop="content">
            <div class="flex start mt30">
              <div class="goods-content-editor mr50">
                <editor
                  ref="editorRef"
                  height="600px"
                  v-model="createForm.content"
                ></editor>
              </div>
              <phone-preview v-model="createForm.content"> </phone-preview>
            </div>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="物流设置" :name="4">
          <div class="form-main">
            <div class="form-main-item">
              <el-form-item
                label="配送方式："
                prop="delivery_type"
                class="form-main-item-input"
              >
                <el-checkbox-group v-model="createForm.delivery_type">
                  <template
                    v-for="(item, index) in DeliveryTypeEnum"
                    :key="index"
                  >
                    <el-checkbox :label="item.value">{{
                      item.name
                    }}</el-checkbox>
                  </template>
                </el-checkbox-group>
              </el-form-item>
            </div>
            <div
              class="form-main-item"
              v-if="$utils.inArray('express', createForm.delivery_type)"
            >
              <el-form-item
                label="运费设置："
                prop="delivery_shipping"
                class="form-main-item-input"
              >
                <el-radio-group v-model="createForm.delivery_shipping">
                  <template
                    v-for="(item, index) in DeliveryShippingEnum"
                    :key="index"
                  >
                    <el-radio :label="item.value">{{ item.name }}</el-radio>
                  </template>
                </el-radio-group>
              </el-form-item>
            </div>
            <div
              class="form-main-item"
              v-if="createForm.delivery_shipping == 2"
            >
              <el-form-item
                label="运费："
                prop="delivery_shipping_price"
                class="form-main-item-input"
              >
                <el-input
                  type="number"
                  v-model="createForm.delivery_shipping_price"
                  placeholder="请输入运费"
                >
                  <template #suffix> 元 </template>
                </el-input>
              </el-form-item>
            </div>
            <div
              class="form-main-item"
              v-if="createForm.delivery_shipping == 3"
            >
              <el-form-item
                label="运费模板："
                prop="delivery_shipping_temp_id"
                class="form-main-item-input"
              >
                <el-select
                  v-model="createForm.delivery_shipping_temp_id"
                  placeholder="请选择运费模版"
                  class="form-select-fil"
                >
                  <el-option
                    v-for="item in templatesData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <div
                class="form-main-item-btn ml20"
                @click="createShippingTemplate"
              >
                新增运费模版
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="营销设置" :name="5">
          <div class="form-main">
            <div class="form-main-item">
              <el-form-item
                class="form-main-item-input"
                label="商品服务："
                prop="goods_server"
              >
                <div class="flex">
                  <el-checkbox-group v-model="createForm.goods_server">
                    <template
                      v-for="(item, index) in goodsServerData"
                      :key="index"
                    >
                      <el-checkbox :label="item.id">{{
                        item.server_name
                      }}</el-checkbox>
                    </template>
                  </el-checkbox-group>
                </div>
                <div
                  class="form-main-item-btn"
                  @click="createGoodsServerTemplate"
                >
                  新增服务
                </div>
              </el-form-item>
            </div>
            <div class="form-main-item">
              <el-form-item
                class="form-main-item-input"
                label="是否限购："
                prop="buy_limit_status"
              >
                <el-switch
                  v-model="createForm.buy_limit_status"
                  inline-prompt
                  :active-value="1"
                  :inactive-value="0"
                  active-text="开启"
                  inactive-text="关闭"
                />
              </el-form-item>
            </div>
            <div class="form-main-item" v-if="createForm.buy_limit_status">
              <el-form-item label="限购类型：" prop="buy_limit_type">
                <el-radio-group v-model="createForm.buy_limit_type">
                  <el-radio :label="0">单次限购</el-radio>
                  <el-radio :label="1">长期限购</el-radio>
                </el-radio-group>
                <help hideIcon
                  ><div>单次限购是限制每次下单最多购买的数量</div>
                  <div>长期限购是限制一个用户总共可以购买的数量</div></help
                >
              </el-form-item>
            </div>
            <div class="form-main-item" v-if="createForm.buy_limit_status">
              <el-form-item
                label="限购数量："
                prop="buy_limit"
                class="form-main-item-input"
              >
                <el-input
                  v-model="createForm.buy_limit"
                  :min="0"
                  placeholder="请输入限购数量"
                ></el-input>
              </el-form-item>
            </div>

            <div class="form-main-item">
              <el-form-item
                class="form-main-item-input"
                label="是否起售要求："
                prop="buy_least_status"
              >
                <el-switch
                  v-model="createForm.buy_least_status"
                  inline-prompt
                  :active-value="1"
                  :inactive-value="0"
                  active-text="开启"
                  inactive-text="关闭"
                />
              </el-form-item>
            </div>
            <div class="form-main-item" v-if="createForm.buy_least_status">
              <el-form-item label="起售要求类型：" prop="buy_least_type">
                <el-radio-group v-model="createForm.buy_least_type">
                  <el-radio :label="0">单次起售</el-radio>
                  <el-radio :label="1">叠加起售</el-radio>
                </el-radio-group>
                <help hideIcon
                  ><div>单次起售是要求每次下单最少购买的数量</div>
                  <div>叠加起售是要求一个用户最少购买的数量</div></help
                >
              </el-form-item>
            </div>
            <div class="form-main-item" v-if="createForm.buy_least_status">
              <el-form-item
                label="起售数量："
                prop="buy_least"
                class="form-main-item-input"
              >
                <el-input
                  v-model="createForm.buy_least"
                  :min="0"
                  placeholder="请输入起售数量"
                ></el-input>
              </el-form-item>
            </div>

            <div class="form-main-item">
              <el-form-item
                class="form-main-item-input"
                label="虚拟销量："
                prop="sales_initial"
              >
                <el-input-number v-model="createForm.sales_initial" :min="0" />
              </el-form-item>
            </div>
            <div class="form-main-item">
              <el-form-item
                class="form-main-item-input"
                label="排序："
                prop="sort"
              >
                <el-input-number v-model="createForm.sort" :min="0" />
              </el-form-item>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="其他设置" :name="6">
          <div class="form-main">
            <el-form-item
              class="form-main-item-input"
              label="商品关键字："
              prop="keywords"
            >
              <el-input
                type="textarea"
                v-model="createForm.keywords"
                placeholder="请输入商品关键字"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="form-main-item-input"
              label="商品卖点	："
              prop="selling_point"
            >
              <el-input
                type="textarea"
                v-model="createForm.selling_point"
                placeholder="请输入商品卖点/简介"
              ></el-input>
            </el-form-item>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-form-item>
        <div class="mt50 mb50">
          <template v-if="tabIndex > 1">
            <el-button @click="step(0, createRef)">上一步</el-button>
          </template>
          <template v-if="tabIndex < 6">
            <el-button @click="step(1, createRef)" type="primary"
              >下一步</el-button
            >
          </template>
          <el-button
            v-if="tabIndex == 6 || true"
            :loading="btnLoading"
            :disabled="btnLoading"
            @click="save(createRef)"
            type="primary"
            >保存</el-button
          >
        </div>
      </el-form-item>
    </el-form>

    <!-- 添加商品标签组件 -->
    <createGoodsLabelCreate
      ref="createGoodsLabelCreateRef"
      @success="toInit()"
    ></createGoodsLabelCreate>
    <!-- 添加商品单位组件 -->
    <storeGoodsUnitCreate
      ref="storeGoodsUnitCreateRef"
      @success="toInit"
    ></storeGoodsUnitCreate>
    <!-- 添加商品分类组件 -->
    <storeGoodsCateCreate
      ref="storeGoodsCateCreateRef"
      @success="toInit()"
    ></storeGoodsCateCreate>
    <!-- 添加运费模版组件 -->
    <storeShippingTemplatesCreate
      ref="storeShippingTemplatesCreateRef"
      @success="toInit()"
    ></storeShippingTemplatesCreate>
    <!-- 添加规格模版组件 -->
    <storeGoodsSpecTemplatesCreate
      ref="storeGoodsSpecTemplatesCreateRef"
      @success="toInit()"
    ></storeGoodsSpecTemplatesCreate>
    <!-- 添加商品服务组件 -->
    <storeGoodsServerCreate
      ref="storeGoodsServerCreateRef"
      @success="toInit"
    ></storeGoodsServerCreate>
  </layout-body>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, getCurrentInstance, watch } from "vue";
import { getGoodsCateList } from "@/api/store/goods_cate";
import { getGoodsUnitSelect } from "@/api/store/goods_unit";
import { getGoodsLabelSelect } from "@/api/store/goods_label";
import { getShippingTemplatesSelect } from "@/api/store/shipping_templates";
import { getGoodsSpecTemplatesSelect } from "@/api/store/goods_spec_templates";
import { getGoodsServerSelect } from "@/api/store/goods_server";

import storeGoodsCateCreate from "./../goods_cate/create.vue";
import storeGoodsUnitCreate from "./../goods_unit/create.vue";
import createGoodsLabelCreate from "./../goods_label/create.vue";
import storeShippingTemplatesCreate from "./../shipping_templates/create.vue";
import storeGoodsSpecTemplatesCreate from "./../goods_spec_templates/create.vue";
import storeGoodsServerCreate from "./../goods_server/create.vue";
import storeGoodsSpec from "@/components/goods-spec/index.vue";
import { Result, ResultError } from "@/types";
import type { FormInstance } from "element-plus";
import { split } from "lodash";
import {
  getGoodsDetail,
  createGoodsSpec,
  createGoods,
  updateGoods,
} from "@/api/store/goods";
import router from "@/router";
import { useConfig } from "@/store";
import { Console } from "console";
const configStore = useConfig();

const {
  proxy,
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const specTypeEnum = ref(configStore.getEnumItem("store.goods.SpecTypeEnum"));
const DeliveryTypeEnum = ref(configStore.getEnumItem("store.DeliveryTypeEnum"));
const DeliveryShippingEnum = ref(
  configStore.getEnumItem("store.DeliveryShippingEnum")
);

const initLoading = ref<boolean>(true);

const specForm = ref<
  Array<{
    name: string;
    key: string;
    type?: string;
    unit?: string;
    required?: boolean;
    input_type?: string;
  }>
>([
  {
    name: "图片",
    key: "goods_img",
    type: "image",
  },
  {
    name: "售价",
    key: "price",
    type: "input",
    unit: "元",
    required: true,
  },
  {
    name: "成本价",
    key: "cost_price",
    type: "input",
    unit: "元",
    required: true,
  },
  {
    name: "市场价",
    key: "market_price",
    type: "input",
    unit: "元",
    required: true,
  },
  {
    name: "库存",
    key: "stock",
    type: "input",
    required: true,
  },
  {
    name: "商品编号",
    key: "bar_code",
    type: "input",
    input_type: "text",
  },
  {
    name: "重量(KG)",
    key: "weight",
    type: "input",
  },
  {
    name: "体积(m³)",
    key: "volume",
    type: "input",
  },
]);

const createRef = ref<HTMLElement>();

const specFormValue = ref<object>({
  goods_img: "",
  price: "",
  cost_price: "",
  market_price: "",
  stock: "",
  bar_code: "",
  weight: "",
  volume: "",
});

const createForm = ref<any>({
  cate_id: [],
  goods_name: "",
  goods_unit: null,
  goods_code: "",
  goods_imgs: "",
  goods_label: [],
  spec_type: 1,
  spec: [
    {
      ...specFormValue.value,
    },
  ],
  delivery_type: ["express"],
  delivery_shipping: 1,
  delivery_shipping_temp_id: null,
  delivery_shipping_price: "",
  content: "",
  sales_initial: 0,
  sort: 0,
  keywords: "",
  selling_point: "",
  goods_server: [],
  buy_limit_status: 0,
  buy_limit: 0,
  buy_limit_type: 0,
  buy_least_status: 0,
  buy_least: 0,
  buy_least_type: 0,
});

// 修改的规格数据
const updateSpecData = ref<any>([]);

const contentValid = (rule: any, value: any, callback: any) => {
  if (value === "" || value === "<p><br></p>") {
    callback(false);
  } else {
    callback();
  }
};
const deliveryPriceValid = (rule: any, value: any, callback: any) => {
  if (
    $utils.inArray("slef_mention", createForm.value.delivery_type) &&
    createForm.value.delivery_shipping == 2 &&
    value === ""
  ) {
    callback(false);
  } else {
    callback();
  }
};
const specValid = (rule: any, value: any, callback: any) => {
  if (createForm.value.spec_type == 2 && createForm.value.spec.length == 0) {
    callback("多规格不能为空");
  } else {
    callback();
  }
};
const buyLimitValid = (rule: any, value: any, callback: any) => {
  if (
    createForm.value.buy_limit_status &&
    createForm.value.buy_least_status &&
    Number(createForm.value.buy_least) > Number(createForm.value.buy_limit)
  ) {
    callback("限购不能小于起购要求!");
  } else {
    callback();
  }
};
const createRules: any = reactive({
  cate_id: [{ required: true, message: "请选择商品分类" }],
  goods_name: [{ required: true, message: "请输入商品名称！" }],
  delivery_type: [{ required: true, message: "请选择配送方式！" }],
  goods_imgs: [{ required: true, message: "商品图片不能为空！" }],
  content: [{ validator: contentValid, message: "商品详细不能为空！" }],
  delivery_shipping_price: [
    { validator: deliveryPriceValid, message: "请输入固定邮费！" },
  ],
  buy_limit: [{ validator: buyLimitValid, trigger: "blur" }],
  buy_least: [{ validator: buyLimitValid, trigger: "blur" }],
});

const toInit = () => {
  toCateInit();
  toUnitInit();
  toLabelInit();
  toShippingTemplatesInit();
  toSpecTemplatesInit();
  toServerInit();
  if (operationId.value != 0) {
    getGoodsDetail({
      id: operationId.value,
    })
      .then((res: Result) => {
        var goods = res.data.detail;
        createForm.value.goods_name = goods.goods_name;
        createForm.value.goods_imgs = goods.goods_imgs;
        createForm.value.goods_unit = goods.goods_unit || null;
        createForm.value.keywords = goods.keywords;
        createForm.value.sales_initial = goods.sales_initial;
        createForm.value.selling_point = goods.selling_point;
        createForm.value.sort = goods.sort;
        createForm.value.delivery_shipping = goods.delivery_shipping.value;
        createForm.value.delivery_shipping_price =
          goods.delivery_shipping_price;
        createForm.value.delivery_shipping_temp_id =
          goods.delivery_shipping_temp_id;
        createForm.value.delivery_type = goods.delivery_type;
        createForm.value.spec_type = goods.spec_type.value;

        createForm.value.buy_limit_status = goods.buy_limit_status;
        createForm.value.buy_limit = goods.buy_limit;
        createForm.value.buy_limit_type = goods.buy_limit_type;
        createForm.value.buy_least_status = goods.buy_least_status;
        createForm.value.buy_least = goods.buy_least;
        createForm.value.buy_least_type = goods.buy_least_type;

        if (createForm.value.spec_type == 2) {
          updateSpecData.value = goods.sku;
          specData.value = res.data.spec;
          getAttrForm(res.data.spec_attr);
        } else {
          createForm.value.spec = goods.sku;
        }

        createForm.value.content = goods.content;
        proxy?.$refs["editorRef"]?.setContent(goods.content);
        createForm.value.cate_id = $utils.getArrayColumnByKey(goods.cate, "id");
        createForm.value.goods_label = $utils.getArrayColumnByKey(
          goods.label,
          "id"
        );
        createForm.value.goods_server = $utils.getArrayColumnByKey(
          goods.server,
          "id"
        );

        initLoading.value = false;
      })
      .catch((err: ResultError) => {
        $utils.errorMsg(err);
        router.back();
        initLoading.value = false;
      });
  } else {
    initLoading.value = false;
  }
};

const cateData = ref<any>([]);
const unitData = ref<any>([]);
const labelData = ref<any>([]);

const toCateInit = () => {
  getGoodsCateList({})
    .then((res: Result) => {
      cateData.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const storeGoodsCateCreateRef = ref<HTMLElement>();

const createCate = () => {
  proxy?.$refs["storeGoodsCateCreateRef"]?.open();
};

const toUnitInit = () => {
  getGoodsUnitSelect()
    .then((res: Result) => {
      unitData.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const storeGoodsUnitCreateRef = ref<HTMLElement>();

const createUnit = () => {
  proxy?.$refs["storeGoodsUnitCreateRef"]?.open();
};

const toLabelInit = () => {
  getGoodsLabelSelect()
    .then((res: Result) => {
      labelData.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const templatesData = ref<any>([]);

const toShippingTemplatesInit = () => {
  getShippingTemplatesSelect()
    .then((res: Result) => {
      templatesData.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const storeGoodsSpecRef = ref<HTMLElement>();

const specTemplatesData = ref<any>([]);

const specTemplatesId = ref<number | unknown>(null);

const toSpecTemplatesInit = () => {
  getGoodsSpecTemplatesSelect()
    .then((res: Result) => {
      specTemplatesData.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const storeGoodsServerRef = ref<HTMLElement>();

const goodsServerData = ref<any>([]);

const goodsServerId = ref<number | unknown>(null);

const toServerInit = () => {
  getGoodsServerSelect()
    .then((res: Result) => {
      goodsServerData.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const selectedTemplates = () => {
  if (!specTemplatesId.value) {
    $utils.errorMsg("请先选择规格模版!");
    return false;
  }
  var item = $utils.getArrayItemByKeyValue(
    specTemplatesData.value,
    "id",
    specTemplatesId.value
  );
  specData.value = $utils.toArray(item.attrs) || [];
  proxy?.$refs["storeGoodsSpecRef"]?.refresh(specData.value);
};

const createGoodsLabelCreateRef = ref<HTMLElement>();

const createLabel = () => {
  proxy?.$refs["createGoodsLabelCreateRef"]?.open();
};

const storeShippingTemplatesCreateRef = ref<HTMLElement>();

const createShippingTemplate = () => {
  proxy?.$refs["storeShippingTemplatesCreateRef"]?.open();
};

const storeGoodsSpecTemplatesCreateRef = ref<HTMLElement>();

const createSpecTemplates = () => {
  proxy?.$refs["storeGoodsSpecTemplatesCreateRef"]?.open();
};

const storeGoodsServerCreateRef = ref<HTMLElement>();

const createGoodsServerTemplate = () => {
  proxy?.$refs["storeGoodsServerCreateRef"]?.open();
};

const editorRef = ref<HTMLElement>();

const tabIndex = ref<number>(1);

const tabChange = (val: number) => {
  if (val == 3) {
    proxy?.$refs["editorRef"]?.setFocus();
  }
  tabIndex.value = val;
};
const stepFields = ref<any>([
  [],
  ["cate_id", "goods_name", "goods_imgs", "goods_label", "goods_unit"],
  [],
  ["content"],
  ["delivery_type"],
]);

const step = async (type: number, formEl: typeof FormInstance | undefined) => {
  if (type == 1) {
    if (stepFields.value[tabIndex.value]) {
      stepFields.value[tabIndex.value].forEach((item: any, index: number) => {
        if (typeof item == "object" && item.spec) {
          stepFields.value[tabIndex.value] = [];
          getStepFieldsRules();
        }
      });
      formEl.validateField(
        stepFields.value[tabIndex.value],
        (valid: boolean) => {
          if (valid) {
            tabIndex.value++;
          }
        }
      );
    } else {
      tabIndex.value++;
    }
  } else {
    tabIndex.value--;
  }
};

const getStepFieldsRules = () => {
  stepFields.value[2] = [];
  createForm.value.spec.forEach((obj: any, idx: number) => {
    for (let i in obj) {
      var specItem = $utils.getArrayItemByKeyValue(specForm.value, "key", i);
      if (specItem.required) {
        stepFields.value[2].push(`spec[${idx}].[${i}]`);
      }
    }
  });
  if (createForm.value.spec_type == 2) {
    stepFields.value[2].push(`spec`);
  }
};

const specName = ref<string>("");

const specValue = ref<string[]>([]);

const specData = ref<any>([]);

const createSpecName = () => {
  if (specName.value == "") {
    $utils.errorMsg("请输入规格名");
    return false;
  }
  if (specName.value.indexOf(" ") !== -1) {
    $utils.errorMsg("规格名不能包含空格");
    return false;
  }
  specData.value.push({
    name: specName.value,
    value: [],
  });
  specName.value = "";
};

const saveSpec = (formEl: typeof FormInstance | undefined) => {
  if (specData.value.length == 0) {
    $utils.errorMsg("无规格属性");
    return false;
  }
  createGoodsSpec({ spec: specData.value })
    .then((res: Result) => {
      getAttrForm(res.data, formEl);
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
  // var specList = $utils.getGoodsSpecFormat(specData.value);
  // getAttrForm(specList, formEl);
};

const headColumns = ref<
  Array<{
    name: string;
    key: string;
    type?: string;
    required?: boolean;
    input_type?: string;
  }>
>([]);

const getAttrForm = (
  specList: {
    attrs: Array<{
      name: string;
      img: string;
      id: string;
    }>;
    names: string[];
  },
  formEl: typeof FormInstance | undefined = null
) => {
  var skuValue = [] as Array<any>;
  headColumns.value = [];
  if (specList.attrs.length == 0) {
    $utils.errorMsg("规格值不能为空");
    return false;
  }
  specList.names.forEach((item: string, index: number) => {
    headColumns.value.push({
      name: item,
      key: "attr" + index,
    });
  });
  var headArr = specForm.value;
  headArr.forEach((item: { name: string; key: string; type?: string }) => {
    headColumns.value.push(item);
  });
  specList.attrs.forEach(
    (
      item: {
        name: string;
        img: string;
        id: string;
      },
      index: number
    ) => {
      var attrs =
          String(item.id).indexOf(":") !== -1 ? item.id.split(":") : [item.id],
        names = item.name.split(","),
        attrImg: any = item.img?.split(",") || [],
        attrObj: any = {};
      attrObj["sku_attr"] = item.id;
      attrObj["sku_attr_text"] = item.name;
      for (let i = 0; i < names.length; i++) {
        attrObj = Object.assign(
          {
            ["attr" + i]: {
              img: attrImg[i] || null,
              name: names[i],
              attrs: attrs[i] || "",
            },
          },
          attrObj
        );
      }
      skuValue[index] = Object.assign({ ...specFormValue.value }, attrObj);
    }
  );
  createForm.value.spec = skuValue;
  formEl?.validateField(["spec"], (valid: boolean) => {});
};

const operation = ref<string>("create");

const operationId = ref<number | string>(0);

const btnLoading = ref<boolean>(false);

// 提交
const save = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: boolean, fields: any) => {
    if (valid) {
      if (btnLoading.value) {
        return;
      }
      btnLoading.value = true;
      let operationApi: any = null;
      console.log(createForm.value.spec);
      if (operation.value == "create") {
        operationApi = createGoods(createForm.value);
      } else {
        operationApi = updateGoods(
          Object.assign(
            {
              id: operationId.value,
            },
            createForm.value
          )
        );
      }
      operationApi
        .then((res: Result) => {
          $message.success(res.message);
          btnLoading.value = false;
          router.push({
            path: "/store/goods/list",
          });
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false;
        });
    } else {
      var errFields: string[] = [];
      for (let i in fields) {
        errFields.push(i);
      }
      getStepFieldsRules();
      stepFields.value.forEach((item: any, index: number) => {
        if ($utils.inArray(errFields[0], item)) {
          tabIndex.value = index;
        }
      });
    }
  });
};

watch(
  () => createForm.value.spec_type,
  (val) => {
    if (createForm.value.spec_type == 1) {
      createForm.value.spec = [
        {
          ...specFormValue.value,
        },
      ];
    } else {
      createForm.value.spec = updateSpecData.value;
    }
  },
  { deep: true }
);

onMounted(() => {
  let query = router.currentRoute.value.query;
  if (query && query.id) {
    operationId.value = String(query.id);
    operation.value = "编辑";
  }
  toInit();
});
</script>

<style scoped>
.form-main {
  margin: 30px 0;
}
.form-main-item {
  width: 600px;
  display: flex;
}
.form-main-item-input {
  width: 500px;
}
.form-main-item-btn {
  font-size: 12px;
  line-height: 32px;
  color: var(--base-default);
  cursor: pointer;
  white-space: nowrap;
}
.goods-content-editor {
  width: calc(100% - 380px);
  max-width: 800px;
}
.form-main-item-small {
  width: 200px;
}
</style>